package com.zmn.plat.admin.controller.message;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.constant.StatusConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto.ResultDTO;
import com.zmn.common.dto.StatusDTO;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.cas.model.LoginStaff;
import com.zmn.plat.admin.controller.PlatBaseController;
import com.zmn.plat.manager.constant.MsgTemplateConsts;
import com.zmn.plat.model.entity.message.*;
import com.zmn.plat.services.interfaces.message.*;

import lombok.extern.log4j.Log4j2;

/**
 * 描述: 消息管理修改Controller
 *
 * @auther tanghongjun
 * @since 2019/10/21 16:36
 */
@Controller
@RequestMapping("/msg/temp/")
@Log4j2
public class MsgTemplateModifyController extends PlatBaseController {

    @Autowired
    private MsgTemplateService msgTemplateService;

    @Autowired
    private MsgTemplateConfigService msgTemplateConfigService;

    @Autowired
    MsgWechatTemplateService msgWechatTemplateService;

    @Autowired
    MsgSmsTemplateService msgSmsTemplateService;

    @Autowired
    MsgAliTemplateService msgAliTemplateService;

    @Autowired
    MsgBaiduTemplateService msgBaiduTemplateService;

    /**
     * 修改排序
     *
     * @param templateId
     * @param sort
     * @return
     * @author xiangjunming
     * @since 2019/10/28
     */
    @RequestMapping(value = "modifySort")
    @RequiresPermissions("/msg/temp/addEdit.action")
    @ResponseBody
    public ResponseDTO modifySort(HttpServletRequest request, @RequestParam(value = "id", defaultValue = "0") Integer templateId,
        @RequestParam(value = "sort", defaultValue = "0") Integer sort) {

        if (templateId == 0) {
            return ResponseDTO.fail("请选择要更改的排序！");
        }
        if (sort == 0) {
            return ResponseDTO.fail("请设置排序值！");
        }

        msgTemplateService.updateSortByKey(templateId, sort, getMcStaffRealName());

        return ResponseDTO.success(GlobalConsts.SUCCESS_MSG);
    }

    /**
     * 启用/停用
     *
     * @param ids
     * @param status
     * @return
     * @author xiangjunming
     * @since 2019/10/28
     */
    @RequestMapping(value = "modifyStatus")
    @RequiresPermissions("/msg/temp/modifyStatus.action")
    @ResponseBody
    public ResponseDTO modifyStatus(String ids, int status) {
        if (StringUtil.isBlank(ids)) {
            return ResponseDTO.fail("请选择！");
        }
        LoginStaff mcStaff = getMcStaff();
        List<Integer> templateIds = StringUtil.convertStrsToList(ids);

        if (status == GlobalDict.STATUS_ENABLE) {
            // 校验配置是否完善
            MsgTemplateQuery query = new MsgTemplateQuery();
            query.setTemplateIds(templateIds);
            List<MsgTemplate> msgTemplates = msgTemplateService.listByQuery(query);
            for (MsgTemplate msgTemplate : msgTemplates) {
                boolean flag = checkMsgConfig(msgTemplate) || checkWechatConfig(msgTemplate) || checkAlipayConfig(msgTemplate);
                if (!flag) {
                    return ResponseDTO.fail(String.format("模板名称:%s, 请完成短信、微信、支付宝任意一项配置! ", msgTemplate.getName()));
                }

                if (msgTemplate.getTemplateType() == MsgTemplateConsts.MSG_TEMP_TYPE_CITY
                    || msgTemplate.getTemplateType() == MsgTemplateConsts.MSG_TEMP_TYPE_CHANNEL_CITY) {
                    List<MsgTemplateConfigVO> cityConfigs =
                        msgTemplateConfigService.listByTemplateIdAndType(msgTemplate.getTemplateId(), MsgTemplateConsts.MSG_TEMP_TYPE_CITY);
                    if (cityConfigs == null || cityConfigs.size() == 0) {
                        return ResponseDTO.fail(String.format("模板名称:%s, 请完成一项城市配置! ", msgTemplate.getName()));
                    }
                }

                if (msgTemplate.getTemplateType() == MsgTemplateConsts.MSG_TEMP_TYPE_CHANNEL
                    || msgTemplate.getTemplateType() == MsgTemplateConsts.MSG_TEMP_TYPE_CHANNEL_CITY) {
                    List<MsgTemplateConfigVO> channelConfigs = msgTemplateConfigService.listByTemplateIdAndType(msgTemplate.getTemplateId(),
                        MsgTemplateConsts.MSG_TEMP_TYPE_CHANNEL);
                    if (channelConfigs == null || channelConfigs.size() == 0) {
                        return ResponseDTO.fail(String.format("模板名称:%s, 请完成一项渠道配置! ", msgTemplate.getName()));
                    }
                }
            }

            // 通用模板
            List<MsgTemplate> currencyTemplates = msgTemplates.stream()
                .filter(item -> item.getTemplateType() == MsgTemplateConsts.MSG_TEMP_TYPE_CURRENCY).collect(Collectors.toList());

            if (currencyTemplates != null && currencyTemplates.size() > 0) {

                // 取第一个通用模板
                MsgTemplate currencyTemplate = currencyTemplates.remove(0);

                if (currencyTemplates.size() > 0) {
                    // 排除剩余通用模板
                    List<Integer> currencyTemplateIds =
                        currencyTemplates.stream().map(MsgTemplate::getTemplateId).collect(Collectors.toList());
                    templateIds = templateIds.stream().filter(p -> !currencyTemplateIds.contains(p)).collect(Collectors.toList());
                }

                // 一个模板组只能启用一个通用模板, 自动停用其他通用模板
                MsgTemplateQuery templateQuery = new MsgTemplateQuery();
                templateQuery.setGroupId(currencyTemplate.getGroupId());
                templateQuery.setTemplateType(MsgTemplateConsts.MSG_TEMP_TYPE_CURRENCY);
                List<MsgTemplate> msgTemplateList = msgTemplateService.listByQuery(templateQuery);
                if (msgTemplateList.size() > 0) {
                    List<Integer> currencyTemplateIds =
                        msgTemplateList.stream().map(MsgTemplate::getTemplateId).collect(Collectors.toList());
                    StatusDTO statusDTO = new StatusDTO();
                    statusDTO.setIds(currencyTemplateIds);
                    statusDTO.setStatus(GlobalConsts.NO);
                    statusDTO.setUpdater(mcStaff.getRealName());
                    statusDTO.setUpdateTime(DateUtil.getNow());
                    msgTemplateService.updateStatusBatch(statusDTO);
                }
            }
        }

        StatusDTO statusDTO = new StatusDTO();
        statusDTO.setIds(templateIds);
        statusDTO.setStatus(status);
        statusDTO.setUpdater(mcStaff.getRealName());
        statusDTO.setUpdateTime(DateUtil.getNow());
        msgTemplateService.updateStatusBatch(statusDTO);

        return ResponseDTO.success(true,"操作成功！");
    }

    private boolean checkMsgConfig(MsgTemplate msgTemplate) {
        MsgSmsTemplate msgSmsTemplate = msgSmsTemplateService.findByTemplateId(msgTemplate.getTemplateId());
        return !Objects.isNull(msgSmsTemplate) && !NumberUtil.isNullOrZero(msgSmsTemplate.getMsgSmsTemplateId());
    }

    private boolean checkWechatConfig(MsgTemplate msgTemplate) {
        MsgWechatTemplate wechatTemplate =
            msgWechatTemplateService.findMsgWechatTemplateByTemplateIdAndWechatAppId(msgTemplate.getTemplateId(), null);
        return !Objects.isNull(wechatTemplate) && !NumberUtil.isNullOrZero(wechatTemplate.getMsgWechatTemplateId());
    }

    private static boolean checkAlipayConfig(MsgTemplate msgTemplate) {
        if (StringUtil.isBlank(msgTemplate.getAlipayMessage())) {
            return false;
        }
        if (StringUtil.isBlank(msgTemplate.getAlipayTempId())) {
            return false;
        }
        return true;
    }

    /**
     * 新增/修改模板基本信息
     *
     * @param template
     * @return the result dto
     * @author xiangjunming
     * @since 2019/10/28
     */
    @RequestMapping("addEdit")
    @RequiresPermissions("/msg/temp/addEdit.action")
    @ResponseBody
    public ResponseDTO addEdit(@RequestBody MsgTemplate template) {

        String lable = NumberUtil.isNullOrZero(template.getTemplateId()) ? "新增模板" : "修改模板";

        try {
            LoginStaff mcStaff = getMcStaff();
            String realName = mcStaff.getRealName();
            if (NumberUtil.isNullOrZero(template.getTemplateId())) {
                template.setCreater(realName);
                template.setStatus(GlobalConsts.NO);
                msgTemplateService.insert(template);
            } else {
                template.setUpdater(realName);
                msgTemplateService.updateBaseInfoByKey(template);
            }

            return ResponseDTO.success(String.valueOf(template.getTemplateId()), String.format("%s成功！", lable));

        } catch (Exception e) {
            log.error("error:", e);
            return ResponseDTO.fail(String.format("%s失败！", lable));
        }
    }

    /**
     * 修改模板消息内容
     *
     * @param template
     * @return the result dto
     * @author xiangjunming
     * @since 2019/10/28
     * @updater wnagjie 2020-06-23 废弃
     * @see MsgTemplateModifyController#editWeChatContent(java.util.List)
     * @see MsgTemplateModifyController#editSmsContent(com.zmn.plat.model.entity.message.MsgTemplate)
     * @see MsgTemplateModifyController#editZfbContent(com.zmn.plat.model.entity.message.MsgTemplate)
     */
    @RequestMapping("editContent")
    @RequiresPermissions("/msg/temp/addEdit.action")
    @ResponseBody
    @Deprecated
    public ResultDTO editContent(@RequestBody MsgTemplate template) {

        try {
            LoginStaff mcStaff = getMcStaff();
            String realName = mcStaff.getRealName();

            template.setUpdater(realName);
            msgTemplateService.updateContentByKey(template);

            ResultDTO result = new ResultDTO(StatusConsts.STATUS_SUCCESS, "OK", true, "修改成功!");
            result.setId(String.valueOf(template.getTemplateId()));
            return result;

        } catch (Exception e) {
            log.error("error:", e);
            return new ResultDTO(StatusConsts.STATUS_ERROR, "ERROR", false, "修改失败!");
        }
    }

    /**
     * 描述：保存微信配置
     *
     * @param msgTemplates
     *            微信配置数据
     * @return com.zmn.common.dto2.ResponseDTO<java.lang.Boolean>
     * @author wangjie
     * @since 2020/6/22 11:28
     **/
    @ResponseBody
    @RequestMapping("editWeChatContent")
    public ResponseDTO<Boolean> editWeChatContent(@RequestBody List<MsgTemplate> msgTemplates) {

        if (CollectionUtil.isNullOrEmpty(msgTemplates)) {
            return ResponseDTO.fail("修改失败,配置项为空");
        }
        try {
            String operatorName = getMcStaff().getRealName();
            Date now = DateUtil.getNow();
            List<MsgWechatTemplate> msgWechatTemplates = msgTemplates.stream()
                .map(mm -> MsgWechatTemplate.builder().templateId(mm.getTemplateId()).wechatId(mm.getThirdAppId())
                    .wechatMessage(mm.getWechatMessage()).wechatEndMessage(mm.getWechatEndMessage()).wechatTempId(mm.getWechatTempId())
                    .status(GlobalConsts.YES).creater(operatorName).createTime(now).updater(operatorName).updateTime(now).build())
                .collect(Collectors.toList());
            msgWechatTemplateService.insertBatch(msgWechatTemplates);
            return ResponseDTO.success(true, "操作成功");
        } catch (Exception e) {
            log.error("[{}],保存微信配置失败,msg:{}", "模板管理-消息内容", e.getMessage(), e);
            return ResponseDTO.fail(e.getMessage());
        }
    }

    /**
     * 描述：保存短信配置
     *
     * @param msgTemplate
     *            短信配置数据
     * @return com.zmn.common.dto2.ResponseDTO<java.lang.Boolean>
     * @author wangjie
     * @since 2020/6/22 11:28
     **/
    @ResponseBody
    @RequestMapping("editSmsContent")
    public ResponseDTO<Boolean> editSmsContent(@RequestBody MsgTemplate msgTemplate) {

        if (Objects.isNull(msgTemplate)) {
            return ResponseDTO.fail("修改失败,配置项为空");
        }
        try {
            String operatorName = getMcStaff().getRealName();
            Date now = DateUtil.getNow();
            MsgSmsTemplate smsTemplate = BeanMapper.map(msgTemplate, MsgSmsTemplate.class);
            smsTemplate.setCreater(operatorName);
            smsTemplate.setUpdater(operatorName);
            smsTemplate.setCreateTime(now);
            smsTemplate.setUpdateTime(now);
            smsTemplate.setStatus(GlobalConsts.YES);
            msgSmsTemplateService.insert(smsTemplate);
            return ResponseDTO.success(true, "操作成功");
        } catch (Exception e) {
            log.error("[{}],保存短信配置失败,msg:{}", "模板管理-消息内容", e.getMessage(), e);
            return ResponseDTO.fail(e.getMessage());
        }
    }

    /**
     * 描述：保存支付宝配置
     *
     * @param msgTemplate
     *            短信支付宝数据
     * @return com.zmn.common.dto2.ResponseDTO<java.lang.Boolean>
     * @author wangjie
     * @since 2020/6/22 11:28
     **/
    @ResponseBody
    @RequestMapping("editZfbContent")
    public ResponseDTO<Boolean> editZfbContent(@RequestBody MsgTemplate msgTemplate) {

        if (Objects.isNull(msgTemplate)) {
            return ResponseDTO.fail("修改失败,配置项为空");
        }
        try {
            String operatorName = getMcStaff().getRealName();
            Date now = DateUtil.getNow();
            MsgAliTemplate aliTemplate = BeanMapper.map(msgTemplate, MsgAliTemplate.class);
            aliTemplate.setUpdater(operatorName);
            aliTemplate.setCreater(operatorName);
            aliTemplate.setCreateTime(now);
            aliTemplate.setUpdateTime(now);
            aliTemplate.setStatus(GlobalConsts.YES);
            msgAliTemplateService.insert(aliTemplate);
            return ResponseDTO.success(true, "操作成功");
        } catch (Exception e) {
            log.error("[{}],保存支付宝配置失败,msg:{}", "模板管理-消息内容", e.getMessage(), e);
            return ResponseDTO.fail(e.getMessage());
        }
    }

    /**
     * 描述：保存百度模板配置
     *
     * @param msgBaiduTemplate
     *            百度模板数据
     * @return com.zmn.common.dto2.ResponseDTO<java.lang.Boolean>
     * @author wangjie
     * @since 2020/6/22 11:28
     **/
    @ResponseBody
    @RequestMapping("editBaiduContent")
    public ResponseDTO<Boolean> editBaiduContent(@RequestBody MsgBaiduTemplate msgBaiduTemplate) {

        if (Objects.isNull(msgBaiduTemplate)) {
            return ResponseDTO.fail("修改失败,配置项为空");
        }
        try {
            Date now = DateUtil.getNow();
            String realName = getMcStaff().getRealName();
            msgBaiduTemplate.setCreater(realName);
            msgBaiduTemplate.setCreateTime(now);
            msgBaiduTemplate.setUpdater(realName);
            msgBaiduTemplate.setUpdateTime(now);
            msgBaiduTemplate.setStatus(GlobalConsts.YES);
            msgBaiduTemplateService.insert(msgBaiduTemplate);
            return ResponseDTO.success(true, "操作成功");
        } catch (Exception e) {
            log.error("[{}],保存百度模板配置失败,msg:{}", "模板管理-消息内容", e.getMessage(), e);
            return ResponseDTO.fail(e.getMessage());
        }
    }
}
